package com.qmyx.supply.admin.controller;

import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.fastjson.JSONObject;
import com.ytjj.qmyx.supplychain.common.api.CommonResult;
import com.ytjj.qmyx.supplychain.common.api.ResultCode;
import com.ytjj.qmyx.supplychain.common.exception.ApiException;
import com.ytjj.qmyx.supplychain.common.model.request.OrdersRequest;
import com.ytjj.qmyx.supplychain.common.model.request.ReconciliationOtherMoneyRequest;
import com.ytjj.qmyx.supplychain.common.model.request.ReconciliationRequest;
import com.ytjj.qmyx.supplychain.mapper.entity.YxBanker;
import com.ytjj.qmyx.supplychain.service.BankerService;
import com.ytjj.qmyx.supplychain.service.ReconciliationService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 财务管理
 * <p>
 * 财务对账
 */

@Slf4j
@RestController
@RequestMapping("/reconciliation")
public class ReconciliationController {

    @Resource
    private ReconciliationService reconciliationService;
    @Autowired
    private BankerService bankerService;

    //账单模板路径
    @Value("${reconciliation.template.path:}")
    private String reconciliationTemplatePath;


    /**
     * 根据条件获取账单
     */
    @PostMapping("/getReconciliationList")
    public CommonResult getReconciliationList(@RequestBody ReconciliationRequest request) {
        YxBanker userInfo = bankerService.getUserInfo();
        request.setBankerId(userInfo.getId());
        return reconciliationService.getReconciliationList(request);
    }

    /**
     * 根据账单id查该账单的订单信息
     */
    @GetMapping("/getReconciliationOrders")
    public CommonResult getReconciliationOrders(@RequestParam Integer id,
                                                @RequestParam(required = false, defaultValue = "1") Integer pageNum,
                                                @RequestParam(required = false, defaultValue = "10") Integer pageSize) {
        return reconciliationService.getReconciliationOrders(id,pageNum,pageSize);
    }

    /**
     * 根据账单id查该账单的订单信息
     */
    @GetMapping("/getReconciliationReturn")
    public CommonResult getReconciliationReturn(@RequestParam Integer id,
                                                @RequestParam(required = false, defaultValue = "1") Integer pageNum,
                                                @RequestParam(required = false, defaultValue = "10") Integer pageSize) {
        return reconciliationService.getReconciliationReturn(id,pageNum,pageSize);
    }


    /**
     * 账单(其他金额)下载模板
     * @param response
     */
    @GetMapping("/downloadTemplate")
    @ResponseBody
    public void downloadTemplate(HttpServletResponse response) {
        try {
            log.info("==============下载模板路径================={}",reconciliationTemplatePath);
            // path是指欲下载的文件的路径。
            File file = new File(reconciliationTemplatePath);
            // 以流的形式下载文件。
            InputStream fis = new BufferedInputStream(new FileInputStream(reconciliationTemplatePath));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            // 清空response
            response.reset();
            response.reset();
            response.addHeader("Access-Control-Allow-Origin", "*");
            response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
            response.addHeader("Access-Control-Allow-Headers", "Content-Type");
            response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(file.getName(),"utf-8"));
            response.addHeader("Content-Length", "" + file.length());
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            toClient.write(buffer);
            toClient.flush();
            toClient.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    /**
     * 账单上传其他金额表格文件
     * @param file
     * @param reconciliationId (账单id)
     */
    @PostMapping("/uploadFile")
    public CommonResult uploadFile(MultipartFile file,Integer reconciliationId) throws IOException {
        // 导入订单
        Sheet sheet = new Sheet(1, 1, ReconciliationOtherMoneyRequest.class);
        SimpleDateFormat sdfs = new SimpleDateFormat("yyyyMMddHHmmss");
        String format = sdfs.format(new Date());
        String fileName = "供应商" + format;

        List<Object> list = new ArrayList<>();
        try {
            list = EasyExcelFactory.read(new BufferedInputStream(file.getInputStream()), sheet);
        } catch (Exception e) {
            throw new ApiException("请导入正确的格式");
        }
        log.info("表格数据：{}", JSONObject.toJSONString(list));
        if (list.size() == 0) {
            throw new ApiException("请导入正确的格式");
        }
        Map map = reconciliationService.uploadDate(list.stream()
                .map(item -> (ReconciliationOtherMoneyRequest) item)
                .collect(Collectors.toList()), reconciliationId, fileName, "banker");
        return CommonResult.success(map);
    }

    /**
     * 获取账单上传的文件
     */
    @GetMapping("/getFileName")
    public CommonResult getFileName(@RequestParam Integer reconciliationId){
        return reconciliationService.getFileName(reconciliationId);
    }

    /**
     * 获取上传文件的数据
     * @param reconciliationId
     * @param source
     * @return
     */
    @GetMapping("/getOtherMoneyDate")
    public CommonResult getOtherMoneyDate(@RequestParam Integer reconciliationId, @RequestParam String source) {
        return reconciliationService.getOtherMoneyDate(reconciliationId,source);
    }

    /**
     * 下载账单
     */
    @GetMapping("/downloadReconciliation")
    public CommonResult downloadReconciliation(@RequestParam Integer reconciliationId){
        return reconciliationService.downloadReconciliation(reconciliationId);
    }
    /**
     * 提交账单
     */
    @GetMapping("/submitReconciliation")
    public CommonResult submitReconciliation(@RequestParam Integer reconciliationId){
        return reconciliationService.submitReconciliation(reconciliationId);
    }


    /**
     * 日结
     * @return
     */
    @GetMapping("/test1")
    public CommonResult test1(@RequestParam(required = false) String dateStr){
        reconciliationService.verifyReconciliationByDay(dateStr);
        return CommonResult.success();
    }

    /**
     * 周结
     * @return
     */
    @GetMapping("/test2")
    public CommonResult test2(){
        reconciliationService.verifyReconciliationByWeek();
        return CommonResult.success();
    }

    /**
     * 月结
     * @return
     */
    @GetMapping("/test3")
    public CommonResult test3(){
        reconciliationService.verifyReconciliationByMonth();
        return CommonResult.success();
    }

    /**
     * 上半月结
     * @return
     */
    @GetMapping("/test4")
    public CommonResult test4(){
        reconciliationService.verifyReconciliationByFirstMonth();
        return CommonResult.success();
    }

    /**
     * 下半月结
     * @return
     */
    @GetMapping("/test5")
    public CommonResult test5(){
        reconciliationService.verifyReconciliationBySecondMonth();
        return CommonResult.success();
    }
}
